//
//  WZTileScrollView.swift
//  WZApp
//
//  Created by evol on 2018/6/8.
//  Copyright © 2018年 evol. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa


class ELTileScrollView: UIView {
    
    let disposeBag = DisposeBag()
    
    let annotationViewAnimateOffset:CGFloat = 14.0 // 标签动画移动幅度
    
    /// 视图部分
    var scrollView:UIScrollView!
    var contentView:UIView!
    var tileView:ELTileView!
    var viewModel:ELTileScrollViewModel!// VM
    // 正在显示的集合
    var visibleAnnotaions = Set<ELAnnotationViewTuple>()
    
    init(_ viewModel:ELTileScrollViewModel) {
        super.init(frame: .zero)
        self.viewModel = viewModel
        setUpView()
    }
    
    private func setUpView(){
        scrollView = UIScrollView()
        scrollView.delegate = self
        scrollView.maximumZoomScale = 8.0
        scrollView.minimumZoomScale = 1.0
        if #available(iOS 11.0, *) {
            scrollView.contentInsetAdjustmentBehavior = .never
        }
        self.addSubview(scrollView!)
        scrollView.snp.makeConstraints({ (make) in
            make.edges.equalTo(self)
        })
        
        // 内容视图
        contentView = UIView()
        scrollView.addSubview(contentView)
        contentView.snp.makeConstraints { (make) in
            make.edges.equalTo(scrollView)
            make.height.equalTo(scrollView)
            make.width.equalTo(APP_RATE*SCENE_SIZE.width)
        }
        
        // 碎片视图 tile
        tileView = ELTileView()
        contentView.addSubview(tileView)
        tileView.snp.makeConstraints { (make) in
            make.edges.equalTo(contentView)
        }
        
        viewModel.classifiedAnnotations.subscribe(onNext:{ // 切换分类, 缩放比例变化都会调用
            [weak self] (result) in
            self?.hideAnnotations()
            self?.updateAnnotations(models: result, offset: (self?.scrollView.contentOffset)!, animate: true)
        }).disposed(by: disposeBag)
        
        scrollView.rx.contentOffset.subscribe(onNext:{
            [weak self](offset) in
            self?.updateAnnotations(models: (self?.viewModel.classifiedAnnotations.value)!, offset: offset, animate:false)
        }).disposed(by: disposeBag)
    }
    
    func hideAnnotations() -> Void {
        for annotation in visibleAnnotaions {
            annotation.view.removeFromSuperview()
            visibleAnnotaions.remove(annotation)
        }
    }
    
    func updateAnnotations(models:[ELTagModel], offset:CGPoint, animate:Bool) -> Void {
        for model in models {
            var annotation = visibleAnnotaions.annotation(model: model) //
            let screen_position = screenPostion(model)
            if bounds.contains(screen_position) {   //  判断屏幕范围内
                
                // 先过滤层级 level
                if CGFloat(model.level!) > CGFloat.maximum(1, scrollView.zoomScale) {
                    if annotation != nil {
                        visibleAnnotaions.remove(annotation!)
                        annotation?.view.removeFromSuperview()
                    }
                    continue
                }
                
                if (annotation != nil) {            // 正在显示的集合里面 更新位置
                    annotation?.view.positon = screen_position
                }else {                             // 没在已经显示的屏幕里面。。
                    let annotationView = ELAnnotationView(model)
                    annotationView.gesture.rx.event.subscribe(onNext:{
                        [weak self] recognizer in
                        self?.viewModel.annotationTapCommand.onNext(model)
                    }).disposed(by: disposeBag)
                    self.addSubview(annotationView)
                    annotation = ELAnnotationViewTuple(model: model, view: annotationView);
                    visibleAnnotaions.insert(annotation!)
                }
                
                if animate {
                    let startPosition = CGPoint(x: screen_position.x, y: screen_position.y + annotationViewAnimateOffset)
                    annotation?.view.alpha = 0
                    annotation?.view.positon = startPosition
                    UIView.animate(withDuration: 0.3) {
                        annotation?.view.alpha = 1
                        annotation?.view.positon = screen_position
                    }
                }else {
                    annotation?.view.positon = screen_position;
                }
            }else { // 不在显示范围内 放到  【复用池】  里面去  先不做复用
                if annotation != nil {
                    annotation?.view.removeFromSuperview()
                    visibleAnnotaions.remove(annotation!)
                }
            }
        }
    }
    
    func screenPostion(_ model:ELTagModel) -> CGPoint {
        return CGPoint(x: APP_RATE*model.x/8 * scrollView.zoomScale - scrollView.contentOffset.x, y: APP_RATE*model.y/8 * scrollView.zoomScale - scrollView.contentOffset.y)
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


extension ELTileScrollView: UIScrollViewDelegate {
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return contentView
    }
}


